package com.demo.las.controller;

import com.demo.las.dto.ApiResponse;
import com.demo.las.dto.PersonalAffairDTO;
import com.demo.las.entity.PersonalAffair;
import com.demo.las.service.PersonalAffairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/personal/affairs")
@CrossOrigin(origins = "*")
public class PersonalAffairController {

    @Autowired
    private PersonalAffairService personalAffairService;

    @GetMapping
    public ApiResponse<List<PersonalAffairDTO>> getAffairs(@RequestParam Long userId) {
        List<PersonalAffairDTO> data = personalAffairService.getAffairsByUser(userId);
        return ApiResponse.success(data);
    }

    @PostMapping
    public ApiResponse<PersonalAffair> createAffair(@Valid @RequestBody PersonalAffair affair) {
        try {
            PersonalAffair saved = personalAffairService.createAffair(affair);
            return ApiResponse.success("个人事务创建成功", saved);
        } catch (Exception e) {
            return ApiResponse.error("创建个人事务失败: " + e.getMessage());
        }
    }

    // 新增：删除个人事务
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteAffair(@PathVariable Long id) {
        try {
            personalAffairService.deleteAffair(id);
            return ApiResponse.success("个人事务删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除个人事务失败: " + e.getMessage());
        }
    }
}